package minesweeper

import (
	"bytes"
	"errors"
)

const testVersion = 1

type Board [][]byte

func (b Board) String() string {
	return "\n" + string(bytes.Join(b, []byte{'\n'}))
}

func (b Board) Count() error {
	if err := valid(b); err != nil {
		return err
	}

	boardLength := len(b[0])
	for i := 1; i < len(b)-1; i++ {
		for j := 1; j < boardLength-1; j++ {
			if b[i][j] == byte(' ') {
				c := 0
				//  up row
				if i-1 > 0 && j-1 > 0 && b[i-1][j-1] == byte('*') {
					c++
				}

				if i-1 > 0 && b[i-1][j] == byte('*') {
					c++
				}

				if i-1 > 0 && j+1 < boardLength-1 && b[i-1][j+1] == byte('*') {
					c++
				}

				// same row
				if j-1 > 0 && b[i][j-1] == byte('*') {
					c++
				}

				if j+1 < boardLength-1 && b[i][j+1] == byte('*') {
					c++
				}

				// down row
				if i+1 > 0 && j-1 > 0 && b[i+1][j-1] == byte('*') {
					c++
				}

				if i+1 > 0 && b[i+1][j] == byte('*') {
					c++
				}

				if i+1 > 0 && j+1 < boardLength-1 && b[i+1][j+1] == byte('*') {
					c++
				}

				if c > 0 {
					b[i][j] = byte(48 + c)
				}
			}
		}
	}

	return nil
}

func valid(b Board) error {
	// check is rectangle ?
	l := len(b[0])
	for i := 1; i < len(b); i++ {
		if l != len(b[i]) {
			return errors.New("is not rectangle")
		}
	}

	// check vertex
	if b[0][0] != byte('+') ||
		b[0][l-1] != byte('+') ||
		b[len(b)-1][0] != byte('+') ||
		b[len(b)-1][l-1] != byte('+') {
		return errors.New("vertex error")
	}

	// check side 1
	for i := 1; i < l-2; i++ {
		if b[0][i] != byte('-') ||
			b[len(b)-1][i] != byte('-') {
			return errors.New("check side 1 error")
		}
	}

	// check side 2
	for i := 1; i < len(b)-2; i++ {
		if b[i][0] != byte('|') ||
			b[i][l-1] != byte('|') {
			return errors.New("check side 2 error")
		}
	}

	boardLength := len(b[0])
	for i := 1; i < len(b)-1; i++ {
		for j := 1; j < boardLength-1; j++ {
			if b[i][j] >= byte('1') && b[i][j] <= byte('9') {
				continue
			}

			if b[i][j] == byte('*') || b[i][j] == byte(' ') {
				continue
			}

			return errors.New("error, ")
		}
	}

	return nil
}
